import { request } from "../utils/request.js";
import { getToken } from "./auth.js";
import { post } from "../store/post/index.js";

export async function createPostAPI(image, description) {
  const formData = new FormData();
  formData.append("file.image", image);
  formData.append("data", JSON.stringify({ description }));

  await fetch("/api/posts", {
    method: "POST",
    body: formData,
    headers: {
      Authorization: `Bearer ${getToken()}`,
    },
  });
}

export async function loadPostsAPI() {
  const result = await request("/api/posts?populate=*");
  return result.map((item) => {
    return {
      id: item.id,
      ...item?.attributes,
      image: post?.attributes?.image?.data?.[0].attributes?.url,
      user: {
        id: post?.attributes?.user?.data?.id,
        ...post?.attributes?.user?.data?.attributes,
      },
    };
  });
}

export async function likePostAPI(id) {
  const res = await request(`/api/posts/${id}/like`, {
    method: "POST",
  });
  return res.data;
}

export async function createCommentAPI(content, postID) {
  await request("/api", {
    method: "POST",
    body: {
      data: {
        content,
        post: postID,
      },
    },
  });
}
